/*
  Optical Heart Rate Detection (PBA Algorithm) using the MAX30105 Breakout
  By: Nathan Seidle @ SparkFun Electronics
  Date: October 2nd, 2016
  https://github.com/sparkfun/MAX30105_Breakout

  This is a demo to show the reading of heart rate or beats per minute (BPM) using
  a Penpheral Beat Amplitude (PBA) algorithm.

  It is best to attach the sensor to your finger using a rubber band or other tightening
  device. Humans are generally bad at applying constant pressure to a thing. When you
  press your finger against the sensor it varies enough to cause the blood in your
  finger to flow differently which causes the sensor readings to go wonky.

  Hardware Connections (Breakoutboard to Arduino):
  -5V = 5V (3.3V is allowed)
  -GND = GND
  -SDA = A4 (or SDA)
  -SCL = A5 (or SCL)
  -INT = Not connected

  The MAX30105 Breakout can handle 5V or 3.3V I2C logic. We recommend powering the board with 5V
  but it will also run at 3.3V.
*/

#include <Wire.h>
#include "MAX30105.h"

#include "heartRate.h"


#include <Arduino.h>
#include <U8g2lib.h>

#include <OneWire.h>
#include <DallasTemperature.h>
// DS18820 用的库

U8G2_SSD1306_128X64_NONAME_F_SW_I2C u8g2(U8G2_R0, /* clock=*/ PB10, /* data=*/ PB11, /* reset=*/ U8X8_PIN_NONE); // U8g2 初始化

MAX30105 particleSensor;  // Max30105 初始化

#define ONE_WIRE_BUS 12  // PA12
OneWire oneWire(ONE_WIRE_BUS);    // 初始连接在单总线上的单总线设备  --- DS18B20 初始化
DallasTemperature sensors(&oneWire);

const byte RATE_SIZE = 4; //Increase this for more averaging. 4 is good.
byte rates[RATE_SIZE]; //Array of heart rates
byte rateSpot = 0;
long lastBeat = 0; //Time at which the last beat occurred

float beatsPerMinute;
int beatAvg;
int showBMP;
float Temp;
String EncodeStr;
void setup()
{
  Serial.begin(115200);
  Serial.println("Initializing...");

  // Initialize sensor
  if (!particleSensor.begin(Wire, I2C_SPEED_FAST)) //Use default I2C port, 400kHz speed
  {
    Serial.println("MAX30105 was not found. Please check wiring/power. ");
    while (1);
  }
  Serial.println("Place your index finger on the sensor with steady pressure.");

  byte ledBrightness = 60; //Options: 0=Off to 255=50mA
  byte sampleAverage = 4; //Options: 1, 2, 4, 8, 16, 32
  byte ledMode = 2; //Options: 1 = Red only, 2 = Red + IR, 3 = Red + IR + Green
  byte sampleRate = 100; //Options: 50, 100, 200, 400, 800, 1000, 1600, 3200
  int pulseWidth = 411; //Options: 69, 118, 215, 411
  int adcRange = 4096; //Options: 2048, 4096, 8192, 16384

  particleSensor.setup(ledBrightness, sampleAverage, ledMode, sampleRate, pulseWidth, adcRange); //Configure sensor with these settings
  particleSensor.setPulseAmplitudeRed(0x0A); //Turn Red LED to low to indicate sensor is running
  particleSensor.setPulseAmplitudeGreen(0); //Turn off Green LED
  
  u8g2.begin();//初始化
  u8g2.enableUTF8Print();   // enable UTF8 support for the Arduino print() function
  u8g2.setFont(u8g2_font_unifont_t_chinese2);
  u8g2.setFontDirection(0);

  sensors.begin();                // 初始库
}

void loop()
{
  long irValue = particleSensor.getIR();

  if (checkForBeat(irValue) == true)
  {
    //We sensed a beat!
    long delta = millis() - lastBeat;
    lastBeat = millis();

    beatsPerMinute = 60 / (delta / 1000.0);

    
    if (beatsPerMinute < 255 && beatsPerMinute > 20)
    {
      rates[rateSpot++] = (byte)beatsPerMinute; //Store this reading in the array
      rateSpot %= RATE_SIZE; //Wrap variable

      //Take average of readings
      beatAvg = 0;
      for (byte x = 0 ; x < RATE_SIZE ; x++)
        beatAvg += rates[x];
      beatAvg /= RATE_SIZE;
    }
  }

  
  if (showBMP != beatAvg ) {
    showBMP = beatAvg;
    u8g2.clearBuffer();
    u8g2.setCursor(0, 15);
    u8g2.print("IR:");
    u8g2.setCursor(40, 15);
    u8g2.print(String(irValue));
    u8g2.setCursor(0, 35);
    u8g2.print("BMP:");
    u8g2.setCursor(40, 35);
    u8g2.print(String(showBMP));
   

    // Show Temp
    sensors.requestTemperatures();  // 发送命令获取温度
    Temp=sensors.getTempCByIndex(0);
    
    u8g2.setCursor(0, 55);
    u8g2.print("Temp:");
    u8g2.setCursor(40, 55);
    u8g2.print(String(Temp));

     u8g2.sendBuffer();

    // 蓝牙发送 
    // 数值编码 ---- 不传中文直接将 数值全部转换成 String
    EncodeStr=String(irValue)+","+String(beatAvg)+","+String(Temp);
    int str_len = EncodeStr.length() + 1;
    char char_array[str_len];
    EncodeStr.toCharArray(char_array, str_len);
    Serial.write(char_array);
  }
//      Serial.print("IR=");
//    Serial.print(irValue);
//    Serial.print(", BPM=");
//    Serial.print(beatsPerMinute);
//    Serial.print(", Avg BPM=");
//    Serial.print(beatAvg);
//    Serial.print(Temp);
//    Serial.println();

}
